package com.education.service.oss.controller;

import com.aliyuncs.exceptions.ClientException;
import com.education.common.utils.FormUtils;
import com.education.common.utils.RandomUtils;
import com.education.exception.OnlineEducationException;
import com.education.result.R;
import com.education.result.ResultCodeEnum;
import com.education.service.oss.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * 阿里云短信发送控制器
 * Created by Lance on 2020/07/04 11:48
 */

@Slf4j
@RestController
@Api(tags = "阿里云短信管理")
@RequestMapping("/web/sms")

public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送短信
     *
     * @param mobile
     * @return
     * @throws ClientException
     */
    @ApiOperation("发送短信")
    @GetMapping("send/{mobile}")
    public R getCode(@ApiParam(value = "请输入合法的手机号码", required = true) @PathVariable String mobile) {

        try {
            //校验手机号是否合法
            if (StringUtils.isEmpty(mobile) || !FormUtils.isMobile(mobile)) {
                log.error("请输入正确的手机号码 ");
                throw new OnlineEducationException(ResultCodeEnum.LOGIN_PHONE_ERROR);
            }

            //生成验证码
            String checkCode = RandomUtils.getSixBitRandom();
            //发送验证码
            smsService.send(mobile, checkCode);

            // 给redis缓存中的手机号验证码分组
            String key = "phoneCode::" + mobile;

            // 将验证码存入redis缓存 并设置过期时间为 5 分钟
            redisTemplate.opsForValue().set(key, checkCode, 5, TimeUnit.MINUTES);

            return R.ok().message("短信发送成功");
        } catch (ClientException e) {
            log.error(ExceptionUtils.getStackTrace(e));
            throw new OnlineEducationException(ResultCodeEnum.SMS_SEND_ERROR);
        }
    }
}
